<template>
	<view class="content">
		<view class="navbar">
			<u-tabs :list="navList" :current="tabCurrentIndex" inactive-color="#333" active-color="#e87722"
				@change="tabClick"></u-tabs>
		</view>

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem, tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData(tabIndex)">
					<!-- 空白页 -->
					<u-empty text="暂无订单" mode="list" v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></u-empty>
					<!-- 订单列表 -->
					<view class="seller-view" :key="oderIndex" v-for="(order, oderIndex) in tabItem.orderList">
						<!-- 店铺名称 -->
						<view class="seller-info u-flex u-row-between">
							<view class="seller-name wes flex justify-between">
								<!-- <view class="name">店铺名称</view> -->
								<view class="ftf40b0b fs-28 rounded">{{order.logistics_type_text}}</view>
								<view class="flex align-center">
									<view class="name u-tag fs-24"
										:style="{'color':renderOrderTagColor(order.status),'border-color':renderOrderTagColor(order.status)}">
										{{orderStatusList[order.status].title}}
									</view>
									<text v-if="isOverdue(order) && order.status == 4" class="name u-tag fs-24"
										:style="{'color':'#e87722','border-color':'#e87722'}">已逾期</text>
								</view>
							</view>
						</view>
						<view>
							<view>
								<view class="goods-item-view" @click="navigateToOrderDetail(order.id)">
									<view class="goods-img">
										<image class="bgf7f7f7 rounded" :src="order.goods_info.goods_img" mode="aspectFill"
											style="width: 100%;height: 100%;"></image>
									</view>
									<view class="goods-info">
										<view class="goods-title u-line-2">
											{{order.goods_info.goods_name}}
										</view>
										<view class="goods-price fs-28 font-weight-bold">
											￥ {{Number(order.sku_data.price/order.sku_data.spec_attrs['租期']).toFixed(2)}}/天
										</view>
									</view>
									<view class="goods-num">
										<view>x{{order.goods_num}}</view>
									</view>
								</view>
							</view>
							<view class=" flex align-center px-2 fs-24 ft666666 pb-2">
								<view class="flex align-center">
									<view class="flex align-center mr-2">
										<div>押金:</div>
										<div class="fs-28 font-weight-bold ">￥{{order.all_deposit_money}}</div>
									</view>
									<view class="flex align-center">
										<div>总租金:</div>
										<div class="fs-28 font-weight-bold price">￥{{order.order_money}}</div>
									</view>
								</view>

								<view class=" flex align-center flex-1 justify-end "
									v-if="overdueTimeShow(order) > 0 && order.status == 4">
									<text>即将逾期：</text>
									<view style="width: 70px;">
										<u-count-down :timestamp="overdueTimeShow(order)" :show-days="false" font-size="24"
											separator-color="#e87722" color="#e87722"></u-count-down>
									</view>
								</view>
							</view>
							<view class="goods-btn flex flex-a-c flex-1 justify-end border-top p-2">
								<view v-if="order.status == '2'" class="pay-btn " size="mini" @click="onRog(order,'orderShip')">
									订单发货
								</view>
								<view v-if="order.status == '5'" ripple shape="circle" class="pay-btn" size="mini"
									@click="onRog(order,'confirmReturn')">
									确认收货
								</view>
							</view>
						</view>
					</view>
					<uni-load-more :status="tabItem.loadStatus"></uni-load-more>
				</scroll-view>
			</swiper-item>
		</swiper>
		<u-popup class="cancel-popup" v-model="cancelShow" mode="bottom" length="60%">
			<view class="header">取消订单</view>
			<view class="body">
				<view class="title">取消订单后，本单享有的优惠可能会一并取消，是否继续？</view>
				<view>
					<u-radio-group v-model="reason">
						<view class="value">
							<view class="radio-view" :key="index" v-for="(item, index) in cancelList">
								<u-radio :active-color="lightColor" label-size="25" shape="circle" :name="item.reason"
									@change="reasonChange">{{ item.reason }}</u-radio>
							</view>
						</view>
					</u-radio-group>
				</view>
			</view>
			<view class="footer">
				<u-button size="medium" ripple v-if="reason" shape="circle" @click="submitCancel">提交</u-button>
			</view>
		</u-popup>
		<!-- <u-modal :confirm-color="lightColor" v-model="rogShow" :show-cancel-button="true" :content="'是否确认收货?'"
			@confirm="confirmRog"></u-modal> -->

		<!--发货-->
		<u-modal :confirm-color="lightColor" v-model="wlShow" :show-cancel-button="true" title="确认发货？" @confirm="confirmWl">
			<view class="flex flex-column align-center pt-5 mb-4 px-2">
				<input class="w-100 text-center" type="text" v-model.trim="logisticsNo" placeholder="请输入物流单号">
			</view>
		</u-modal>

		<!--确认已归还-->
		<u-modal :confirm-color="lightColor" v-model="rogShow" :show-cancel-button="true" title="确认已归还？"
			@confirm="confirmRog">
			<view class="flex flex-column align-center pt-5 mb-4 px-2">
				<!-- <view class="bgf7f7f7 p-2 w-100 box-sizing mb-2 fs-28">未逾期</view> -->
				<view class="bgf7f7f7 p-2 w-100 box-sizing mb-2 fs-28 fte87722">已逾期x天，每日租金x元，逾期租金m元</view>
				<view class="flex align-center fs-28 w-100">
					<text>商品是损坏：</text>
					<view class="flex-1">
						<radio-group @change="radioChange">
							<view class="flex align-center">
								<radio style="transform:scale(0.7)" value="1" :checked="return_condition == 1" />
								<view>否</view>
								<radio style="transform:scale(0.7)" value="2" :checked="return_condition == 2" />
								<view>是</view>
							</view>
						</radio-group>
					</view>
				</view>
				<view class="flex align-center fs-28 w-100 mt-2">
					<text>赔偿押金：</text>
					<view class="flex-1">
						<input class="w-100 fs-24" type="number" v-model.trim="harm_money" placeholder="赔偿押金(元)">
					</view>
				</view>
				<view class="flex align-center fs-28 w-100 mt-2">
					<text>总扣除金额：</text>
					<view class="flex-1">0.00元</view>
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
	import {
		getOrderList,
		orderShip,
		confirmReturn
	} from "@/api/store.js";
	export default {
		components: {
			uniLoadMore,
		},
		data() {
			return {
				lightColor: this.$lightColor,
				tabCurrentIndex: 0, //导航栏索引
				navList: [
					//导航栏list
					{
						state: 0,
						name: "全部",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 0,
						name: "待付款",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 1,
						name: "待自提",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 2,
						name: "待发货",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 10,
						name: "租赁中",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 5,
						name: "待收货",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 6,
						name: "已完成",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
					{
						state: 8,
						name: "已取消",
						loadStatus: "more",
						orderList: [],
						page: 1,
					},
				],
				status: "", //接收导航栏状态
				params: {
					page: 1,
					limit: 10,
					status: "ALL",
				},
				orderStatusList: {
					'0': {
						title: "未付款",
						value: "商品暂未付款",
					},
					'2': {
						title: "待发货",
						value: "商品等待发货中",
					},
					'3': {
						title: "已发货",
						value: "商品已发货,请您耐心等待",
					},
					'4': {
						title: "租赁中",
						value: "商品使用中",
					},
					'10': {
						title: "租赁中",
						value: "商品使用中",
					},
					'5': {
						title: "待收货",
						value: "商品归还中",
					},
					'9': {
						title: "已买断",
						value: "商品已购买",
					},
					'8': {
						title: "已取消",
						value: "订单已取消",
					},
					'6': {
						title: "已完成",
						value: "订单已完成,祝您生活愉快",
					},
					'1': {
						title: "待自提",
						value: "商品正在等待提取",
					},
				},
				orderStatus: [
					//订单状态
					{
						orderStatus: "ALL", //全部
					},
					{
						orderStatus: "0", //待付款
					},
					{
						orderStatus: "1", // 待自提
					},
					{
						orderStatus: "2", // 待发货
					},
					{
						orderStatus: "10", // 租赁中
					},
					{
						orderStatus: "5", //待收货
					},
					{
						orderStatus: "6", //待归还
					},
					{
						orderStatus: "9", //已买断
					},
					{
						orderStatus: "6", //已完成
					},
					{
						orderStatus: "7", //已评价
					},
					{
						orderStatus: "8", //已取消
					},

				],
				cancelShow: false, //是否显示取消
				orderSn: "", //ordersn
				reason: "", //取消原因
				cancelList: "", //取消列表
				rogShow: false, //显示是否收货
				wlShow: false,
				logisticsNo: '',
				return_condition: '1',
				harm_money: '',
				nowTime: 0
			};
		},

		/**
		 * 跳转到个人中心
		 */
		onBackPress(e) {
			if (e.from == "backbutton") {
				uni.switchTab({
					url: "/pages/tabbar/user/my",
				});
				return true; //阻止默认返回行为
			}
		},
		onPullDownRefresh() {
			if (this.tabCurrentIndex) {
				this.initData(this.tabCurrentIndex);
			} else {
				this.initData(0);
			}
			this.loadData(this.status);
		},
		onShow() {
			if (String(this.status) && this.navList[this.tabCurrentIndex].orderList.length) {
				this.navList[this.tabCurrentIndex].page = 1;
				this.loadData(this.tabCurrentIndex);
			}
		},

		onLoad(options) {
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			let status = Number(options.status);
			this.status = status;

			this.tabCurrentIndex = status;
			if (status == 0) {
				this.loadData(status);
			}
		},

		watch: {
			/**监听更改请求数据 */
			tabCurrentIndex(val) {
				if (this.orderStatus[val]) {
					this.params.status = this.orderStatus[val].orderStatus;
					//切换标签页将所有的页数都重置为1
					this.navList.forEach((res) => {
						res.page = 1;
						res.loadStatus = "more";
						res.orderList = [];
					});
					this.loadData(val);
				}
			},
		},
		methods: {
			isOverdue(order) {
				const flag = (new Date(order.recent_end).getTime() + 86400000) - (this.nowTime * 1000) < 0
				if (flag) {
					return true
				}
				return false
			},
			overdueTimeShow(order) {
				const timer = (new Date(order.recent_end).getTime() + 86400000) - (this.nowTime * 1000)
				console.log('timer-----', timer)
				return timer / 1000
			},
			radioChange(evt) {
				this.return_condition = evt.detail.value
			},
			// 售后
			applyService(order) {
				uni.navigateTo({
					url: `/pages/order/afterSales/afterSales?orderSn=${order.sn}`,
				});
			},

			// 店铺详情
			navigateToStore(val) {
				uni.navigateTo({
					url: "/pages/product/shopPage?id=" + val.storeId,
				});
			},
			renderOrderTag(orderPromotionType) {
				switch (orderPromotionType) {
					case "NORMAL":
						return "普通订单";
					case "PINTUAN":
						return "拼团订单";
						break;
					case "GIFT":
						return "赠品订单";
						break;
					case "POINTS":
						return "积分订单";
						break;
					case "KANJIA":
						return "砍价订单";
					default:
						return "";
				}
			},
			renderOrderTagColor(orderPromotionType) {
				switch (String(orderPromotionType)) {
					case "1":
						return "#e87722";
					case "2":
						return "#f40b0b";
					case "4":
						return "blue";
					case "9":
						return "black";
					case "8":
						return "#666666";
					case "6":
						return "#08a51c";
					default:
						return "#2979ff";
				}
			},
			/**
			 * 取消订单
			 */
			onCancel(sn) {
				this.orderSn = sn;
				this.cancelShow = true;
			},

			/**
			 * 初始化数据
			 */
			initData(index) {
				this.navList[index].page = 1;
				this.navList[index].loadStatus = "more";
				this.navList[index].orderList = [];
				this.loadData(index);
			},

			/**
			 * 等待支付
			 */
			waitPay(val) {
				this.$u.debounce(this.pay(val), 3000);
			},

			/**
			 * 支付
			 */
			pay(val) {
				if (val.id) {
					uni.showLoading({
						title: "加载中",
					});
					this.getSignUrl(val)
				}
			},
			getSignUrl(data) {
				//#ifdef MP-ALIPAY
				const url =
					`alipays://platformapi/startapp?appId=2021005176673197&page=/pages/order/orderDetail?sn=${data.id}`
				//#endif
				//#ifdef MP-WEIXIN
				const url = `${config.h5}/pages/h5/h5?sn=${data.id}`
				//#endif
				getSignUrl({
					redirect_url: url,
					order_id: data.id
				}).then(res => {
					uni.hideLoading()
					const url = res.data.sign_url
					uni.redirectTo({
						url: `/pages/navigation/webview?url=${encodeURIComponent(url)}`
					})
				})
			},
			paymentCreate() {
				let submitData = {
					order_id: this.data.sn,
					payment_method: "wechat",
					openid: uni.getStorageSync('openId')
				};
				const paymentMethod = "WECHAT";
				const paymentClient = "MP";
				// 调用支付
				paymentCreate(submitData).then((res) => {
					let response = res.data;
					uni.hideLoading();
					uni.requestPayment({
						provider: "wxpay",
						appid: response.appid,
						timeStamp: response.timeStamp,
						nonceStr: response.nonceStr,
						package: response.package,
						signType: response.signType,
						paySign: response.paySign,
						success: (e) => {
							uni.showToast({
								icon: "none",
								title: "支付成功!",
							});
						},
						fail: (e) => {
							this.exception = e;
							// 支付异常或支付失败之后跳转到订单页面
							uni.showModal({
								content: "支付失败,如果您已支付，请勿反复支付",
								showCancel: false,
								success: () => {
									uni.redirectTo({
										url: "/pages/order/order?status=0",
									});
								},
							});
						},
					});
				});
			},
			/**
			 * 获取订单列表
			 */
			loadData(index) {
				this.params.page = this.navList[index].page;
				const data = {
					...this.params
				}
				if (this.params.status == 'ALL') delete data.status
				getOrderList(data).then((res) => {
					uni.stopPullDownRefresh();
					if (!res.code === 1) {
						this.navList[index].loadStatus = "noMore";
						return false;
					}
					let orderList = res.data.list;
					if (orderList.length == 0) {
						this.navList[index].loadStatus = "noMore";
					} else if (orderList.length < 10) {
						this.navList[index].loadStatus = "noMore";
					}
					if (this.params.page === 1) {
						this.navList[index].orderList = orderList
						if (orderList.length > 9) {
							this.navList[index].page++;
						}
					} else {
						this.navList[index].orderList =
							this.navList[index].orderList.concat(orderList);
						this.navList[index].page++;
					}
					this.nowTime = res.data.now
					console.log('this.navList', this.navList)
				});
			},
			//swiper 切换监听
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
			},
			//顶部tab点击
			tabClick(index) {
				this.tabCurrentIndex = index;
			},
			//删除订单
			deleteOrder(index) {
				uni.showLoading({
					title: "请稍后",
				});
				setTimeout(() => {
					this.navList[this.tabCurrentIndex].orderList.splice(index, 1);
					if (this.$store.state.isShowToast) {
						uni.hideLoading()
					};
				}, 600);
			},
			//取消订单
			cancelOrder(item) {
				uni.showLoading({
					title: "请稍后",
				});
				setTimeout(() => {
					let {
						stateTip,
						stateTipColor
					} = this.orderStateExp(9);
					item = Object.assign(item, {
						state: 9,
						stateTip,
						stateTipColor,
					});

					//取消订单后删除待付款中该项
					let list = this.navList[1].orderList;
					let index = list.findIndex((val) => val.id === item.id);
					index !== -1 && list.splice(index, 1);
					if (this.$store.state.isShowToast) {
						uni.hideLoading()
					};
				}, 600);
			},

			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = "",
					stateTipColor = this.$lightColor;
				switch (+state) {
					case 1:
						stateTip = "待付款";
						break;
					case 2:
						stateTip = "待发货";
						break;
					case 9:
						stateTip = "订单已关闭";
						stateTipColor = "#909399";
						break;

						//更多自定义
				}
				return {
					stateTip,
					stateTipColor,
				};
			},

			/**
			 * 跳转到订单详情
			 */
			navigateToOrderDetail(sn) {
				uni.navigateTo({
					url: "/pages/store/orderDetail?sn=" + sn,
				});
			},

			/**
			 * 选择取消原因
			 */
			reasonChange(reason) {
				this.reason = reason;
			},

			/**
			 * 提交取消订单（未付款）
			 */
			submitCancel() {
				cancelOrder(this.orderSn, {
					reason: this.reason
				}).then((res) => {
					if (res.data.success) {
						uni.showToast({
							title: "订单已取消",
							duration: 2000,
							icon: "none",
						});
						this.initData(this.tabCurrentIndex);

						this.cancelShow = false;
					} else {
						uni.showToast({
							title: res.data.message,
							duration: 2000,
							icon: "none",
						});
						this.cancelShow = false;
					}
				});
			},

			/**
			 * 确认收货显示
			 */
			onRog(order, type) {
				this.orderSn = order;
				if (type == 'orderShip') {
					this.wlShow = true;
				} else if (type == 'confirmReturn') {
					this.rogShow = true;
				}
			},
			confirmWl() {
				if (!this.logisticsNo) {
					uni.showToast({
						title: '请输入物流单号',
						icon: 'none'
					})
					return;
				}
				const data = {
					order_id: this.orderSn.id,
					logistics_no: this.logisticsNo
				}
				orderShip(data).then(res => {
					if (res.code == 1) {
						this.loadData(this.tabCurrentIndex);
					}
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				})
			},
			/**
			 * 点击确认收货
			 */
			confirmRog() {
				const data = {
					order_id: this.orderSn.id
				}
				if (this.return_condition) {
					data.return_condition = this.return_condition == 1 ? '商品未损坏' : '商品已损坏'
				}
				if (this.harm_money) {
					data.harm_money = this.harm_money
				}
				console.log('data-----', data)
				return;
				confirmReturn(data).then((res) => {
					if (res.code == 1) {
						this.initData(this.tabCurrentIndex);
						this.rogShow = false;
					}
					uni.showToast({
						title: res.msg,
						icon: "none",
					});
				}).finally(() => {
					this.return_condition = '1'
					this.harm_money = ''
				})
			},

			/**
			 * 重新购买
			 */
			reBuy(order) {
				console.log(order);
				return;
				uni.navigateTo({
					url: "/pages/product/goods?id=" + order.id + "&goodsId=" + order.goodsId,
				});
			},

			/**
			 * 查看物流
			 */
			navigateToLogistics(order) {
				uni.navigateTo({
					url: "/pages/order/deliverDetail?order_sn=" + order.sn,
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	page,
	.content {
		background: $page-color-base;
		height: 100%;
	}

	.swiper-box {
		height: calc(100vh - 40px);
		// #ifdef H5
		height: calc(100vh - 40px - 44px);
		// #endif
	}

	.list-scroll-content {
		height: 100%;
	}

	.navbar {
		// display: flex;
		height: 40px;
		padding: 0 5px;
		background: #fff;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
		position: relative;
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 26rpx;
			color: #333;
			position: relative;

			&.current {
				color: $main-color;

				&:after {
					content: "";
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 44px;
					height: 0;
					border-bottom: 2px solid $main-color;
				}
			}
		}
	}

	.uni-swiper-item {
		height: auto;
	}

	.seller-view {
		border-radius: 20rpx;
		background-color: #fff;
		margin: 20rpx 10rpx;

		.seller-info {
			height: 70rpx;
			padding: 20rpx 20rpx 0;

			.seller-name {
				flex: 10;
				font-size: 28rpx;
				font-weight: 600;
				display: flex;
				flex-direction: row;
				text-align: center;

				.name {
					margin-left: 15rpx;
				}
			}

			.order-sn {
				flex: 2;
				width: 120rpx;
				text-align: center;
				color: $aider-light-color;
				font-size: 26rpx;
			}
		}

		.goods-item-view {
			display: flex;
			flex-wrap: wrap;
			flex-direction: row;
			padding: 10rpx 20rpx;

			.goods-img {
				width: 131rpx;
				height: 131rpx;
				margin-right: 10rpx;
				margin-bottom: 10rpx;
			}

			.goods-info {
				// padding-left: 30rpx;
				flex: 1;

				.goods-title {
					margin-bottom: 10rpx;
					color: #333333;
				}

				.goods-specs {
					font-size: 24rpx;
					margin-bottom: 10rpx;
					color: #cccccc;
				}

				.goods-price {
					font-size: 28rpx;
					margin-bottom: 10rpx;
					color: $aider-light-color;
				}
			}

			.goods-num {
				width: 60rpx;
				color: $main-color;
			}
		}

		.btn-view {
			padding: 25rpx 30rpx;
			font-size: 26rpx;

			.description {
				display: flex;
				color: #909399;
				size: 24rpx;

				.price {
					color: $main-color;

				}
			}
		}
	}

	.cancel-popup {
		.header {
			display: flex;
			flex-direction: row;
			justify-content: center;
			margin: 15rpx 0rpx;
		}

		.body {
			padding: 30rpx;

			.title {
				font-weight: 600;
			}

			.value {
				display: flex;
				flex-direction: column;
				margin: 20rpx 0;

				.radio-view {
					margin: 20rpx 0rpx;
				}
			}
		}

		.footer {
			text-align: center;
		}
	}

	.goods-btn {
		display: flex;
	}

	.cancel-btn,
	.pay-btn,
	.rebuy-btn {
		text-align: center;
		margin-left: 15rpx;
		font-size: 24rpx;
		padding: 14rpx 20rpx;
		border-radius: 50px;
	}

	.cancel-btn {
		color: #333639 !important;
		background: rgba(46, 51, 56, .05) !important;
	}

	.pay-btn {

		background-color: $light-color !important;

		color: #ffffff !important;
	}

	.rebuy-btn {
		color: $light-color !important;
		border-color: $light-color !important;
		background-color: #ffffff !important;
	}

	.u-tag {
		box-sizing: border-box;
		align-items: center;
		border-radius: 3px;
		display: inline-block;
		border: 1px solid;
		border-color: transparent;
		padding: 2px 10rpx;
	}
</style>